package com.songlanyun.modules.signin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.BeanUtil;
import com.songlanyun.modules.coupon.entity.CouponEntity;
import com.songlanyun.modules.coupon.service.CouponService;
import com.songlanyun.modules.signin.dao.SignInConfigDao;
import com.songlanyun.modules.signin.entity.SignInConfigEntity;
import com.songlanyun.modules.signin.model.dto.SingInConfigDTO;
import com.songlanyun.modules.signin.service.SignInConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 签到管理-签到配置
 *
 * @author lijiahe
 * @date 2022-08-03
 */
@Service("signInConfigService")
public class SignInConfigServiceImpl extends ServiceImpl<SignInConfigDao, SignInConfigEntity>
        implements SignInConfigService {

    @Autowired
    private CouponService couponService;

    @Override
    public SignInConfigEntity get(Boolean tw) {
        SignInConfigEntity entity = baseMapper.selectOne(new LambdaQueryWrapper<SignInConfigEntity>()
                .orderByDesc(SignInConfigEntity::getCreateTime).last("limit 1"));
        if (tw && null == entity) {
            throw new RRException("不存在签到配置");
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrEdit(SingInConfigDTO dto) {
        //校验优惠券
        couponService.loadByCode(dto.getRewardCoupons(), true);

        SignInConfigEntity signInConfigEntity = this.get(false);
        SignInConfigEntity entity = new SignInConfigEntity();
        BeanUtil.copyPropertiesIgnoreNull(dto, entity);

        if (ObjectUtil.isNull(signInConfigEntity)) {
            baseMapper.insert(entity);
        } else {
            entity.setId(signInConfigEntity.getId());
            baseMapper.updateById(entity);
        }
    }

}
